package com.zhongyouyun.admin.service.imp;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongyouyun.admin.model.*;
import com.zhongyouyun.admin.mapper.UserMapper;
import com.zhongyouyun.admin.pojo.UserDetailPojo;
import com.zhongyouyun.admin.pojo.UserPojo;
import com.zhongyouyun.admin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: shenyi
 * @Date: 2021-09-23
 * @Description: 用户表服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, UserModel> implements UserService {

    @Autowired
    private MenuService menuService;
    @Autowired
    private DictService dictService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private DeptService deptService;

    /*
     * @Author: shenyi
     * @Date: 2021-09-08
     * @Description: 分页查询
     * @param page 分页数据  lambdaQueryWrapper where 条件 和排序
     */
    @Override
    public IPage<UserModel> selectPage(Page<UserModel> page, QueryWrapper<UserModel> queryWrapper) {
        return this.baseMapper.selectPage(page, queryWrapper);
    }


    /*
     * @Author: shenyi
     * @Date: 2021-09-08
     * @Description: 查询全部
     * @param   lambdaQueryWrapper where 条件 和排序
     */
    @Override
    public List<UserModel> selectList(QueryWrapper<UserModel> queryWrapper) {
        return this.baseMapper.selectList(queryWrapper);
    }
    @Override
    public List<String> findPermissions(UserModel userModel) {
        List<String> list = new ArrayList<String>();
        List<RoleModel> roleModelList = roleService.findByUserId(userModel.getId());
        roleModelList.forEach(roleModel -> {
            if (roleModel.getId() == 1) {
                QueryWrapper<MenuModel> queryWrapper = new QueryWrapper();
                List<MenuModel> menuModelList = menuService.selectList(queryWrapper);
                menuModelList.forEach(model -> {
                    String perm = model.getPerms();
                    if (StrUtil.isNotEmpty(perm)) {
                        String[] permStr = perm.split(";");
                        for (String s : permStr) {
                            list.add(s);
                        }
                    }
                });
            } else {
                List<DictModel> dictModelList = dictService.selectListbyRoleId(roleModel);
                dictModelList.forEach(model -> {
                    list.add(model.getValue());
                });
            }
        });
        List uniqueStr = list.stream().distinct().collect(Collectors.toList());
        return uniqueStr;
    }



    @Override
    public IPage<UserPojo> selectPojoPage(Page page, QueryWrapper queryWrapper) {
        return this.baseMapper.selectPojoPage(page, queryWrapper);
    }

    @Override
    public UserDetailPojo getDetails(Long id) {
        UserDetailPojo userDetailPojo=this.baseMapper.getDetails(id);
        if (ObjectUtil.isNotEmpty(userDetailPojo)){
           String PIdStr= deptService.getoid(userDetailPojo.getDeptId());
           if (ObjectUtil.isNotEmpty(PIdStr)){
               PIdStr=PIdStr.replace("$,","").replace(",0","");
               String PIdStrZ[]=PIdStr.split(",");
               List<String> list=Arrays.stream(PIdStrZ).collect(Collectors.toList());
               Collections.reverse(list);
               String str = String.join(",", list);
               userDetailPojo.setPId(str);
           }
        }
        return userDetailPojo;
    }

    @Transactional
    public Boolean saveUser(UserModel userModel,String type) {
        String roleIds = userModel.getRoleId();
        String[] roles = roleIds.split(",");
        List<UserRoleModel> userRoleModelList = new ArrayList<UserRoleModel>();
        userModel.setPassword(SecureUtil.md5("123456"));
        Boolean flag = saveOrUpdate(userModel);
        Long userId = userModel.getId();
        for (int i = 0; i < roles.length; i++) {
            String roleId = roles[i];
            UserRoleModel userRoleModel = new UserRoleModel();
            userRoleModel.setRoleId(Long.valueOf(roleId));
            userRoleModel.setUserId(userModel.getId());
            userRoleModel.setCreateBy(userModel.getUpdateBy());
            userRoleModel.setCreateTime(userModel.getUpdateTime());
            userRoleModel.setXiangMuType(type);
            userRoleModel.setUpdateBy(userModel.getUpdateBy());
            userRoleModel.setUpdateTime(userModel.getUpdateTime());
            userRoleModelList.add(userRoleModel);
        }
        QueryWrapper<UserRoleModel> queryWrapper = new QueryWrapper<UserRoleModel>();
        queryWrapper.eq("user_id", userId);
        userRoleService.remove(queryWrapper);
        userRoleService.saveOrUpdateBatch(userRoleModelList);
        return flag;
    }


}
